<?php

namespace app\admin\controller\api;

use app\common\model\DeviceKey;
use think\Validate;

/**
 * 班牌设备
 * @internal
 */
class Device extends Api
{
    protected $noNeedLogin = ['lists', 'getDeviceKeyId', 'active', 'check', 'active'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 设备列表
     *
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $school_id = $this->request->request('school_id');
        $keywords = $this->request->request('keywords');
        $list_rows = $this->request->request('list_rows', 10);

        $result = \app\common\model\Device::alias('device')
            ->join('__DEVICE_KEY__ key', 'key.device_id = device.id', 'inner')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('key|device', 'like', "%$keywords%");
                }
            })
            ->whereIn('device.school_id', [$school_id, 0])
            //->whereIn('key.school_id', [$school_id, 0])
            ->field('key.*')
            ->order('key.status', 'desc')
            ->order('key.id', 'desc')
            ->paginate($list_rows);

        $this->success('', $result);
    }

    public function lists()
    {
        $school_id = $this->request->request('school_id');
        $keywords = $this->request->request('keywords');
        $list_rows = $this->request->request('list_rows', 10);

        $result = \app\common\model\Device::alias('device')
            ->join('__DEVICE_KEY__ key', 'key.device_id = device.id', 'inner')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('key|device', 'like', "%$keywords%");
                }
            })
            ->where('device.school_id', $school_id)
            ->whereIn('key.school_id', [$school_id, 0])
            ->field('key.*')
            ->order('key.status', 'desc')
            ->order('key.id', 'desc')
            ->paginate($list_rows);

        $this->success('', $result);
    }

    /**
     * 根据激活码获取id
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDeviceKeyId()
    {
        $key = $this->request->request('key');
        $result = DeviceKey::where('key', $key)->field('id')->find();
        $this->success('', $result);
    }

    /**
     * 修改
     *
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $params = $this->request->post();
        $validate = Validate::make([
            'id' => 'require',
            'device' => 'require',
            'school_id' => 'require',
            'mac' => 'require',
            'sn' => 'require',
            'model' => 'require',
            'brand' => 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $device_key = DeviceKey::get($params['id']);
        if (!$device_key) {
            $this->error('数据不存在');
        }

        if (DeviceKey::ACTIVATED == $device_key->status) {
            $this->error('设备已激活');
        }

        $params['status'] = DeviceKey::ACTIVATED;
        $result = $device_key->allowField('device,school_id,mac,sn,model,brand,status')->save($params);

        if ($result) {
            $this->success('激活成功');
        } else {
            $this->error('激活失败');
        }

    }

    /**
     * 重置
     *
     * @throws \think\exception\DbException
     */
    public function reset()
    {
        $ids = $this->request->post('ids/a');

        $result = DeviceKey::whereIn('id', $ids)->update([
            'device' => '',
            'school_id' => 0,
            'mac' => '',
            'sn' => '',
            'model' => '',
            'brand' => '',
            'status' => DeviceKey::UNACTIVATED,
        ]);

        if ($result) {
            $this->success('重置成功');
        } else {
            $this->error('重置失败');
        }

    }

    /**
     *  修改名称
     *
     * @throws \think\exception\DbException
     */
    public function editName()
    {
        $id = $this->request->post('id');
        $name = $this->request->post('name');

        $device_key = DeviceKey::get($id);
        if (!$device_key) {
            $this->error('数据不存在');
        }

        $device_key->device = $name;
        $result = $device_key->save();

        if ($result) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }

    }

    /**
     * 检测设备
     */
    public function check()
    {
        $params = $this->request->post();

        $validate = Validate::make([
            'sn' => 'require',
            'model' => 'require',
            'brand' => 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $device_key = DeviceKey::alias('key')
            ->join('__DEVICE__ device', 'device.id = key.device_id')
            ->where([
                'key.sn' => $params['sn'],
                'key.model' => $params['model'],
                'key.brand' => $params['brand'],
            ])
            ->field('key.*,device.app_id,device.sdk_key')->select();

        $this->success('', $device_key);
    }

    /**
     * 激活
     */
    public function active()
    {
        $params = $this->request->post();
        $validate = Validate::make([
            'mac' => 'require',
            'key' => 'require',
            'sn' => 'require',
            'model' => 'require',
            'brand' => 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        //$device_key = DeviceKey::where('key', $params['key'])->find();
        $device_key = DeviceKey::alias('key')
            ->join('__DEVICE__ device', 'device.id = key.device_id')
            ->where([
                'key.key' => $params['key'],
            ])
            ->field('key.*,device.app_id,device.sdk_key')->find();

        if (!$device_key) {
            $this->error('数据不存在');
        }

        if (DeviceKey::ACTIVATED == $device_key->status) {
            $this->error('激活码已使用');
        }

        $count = DeviceKey::where('sn', $params['sn'])->where('brand', $params['brand'])->count();
        if ($count) {
            $this->error('设备已激活');
        }

        $result = $device_key->allowField('mac,sn,model,brand,status')->save([
            'mac' => $params['mac'],
            'sn' => $params['sn'],
            'model' => $params['model'],
            'brand' => $params['brand'],
            'status' => DeviceKey::ACTIVATED,
        ]);

        if ($result) {
            $this->success('激活成功', $device_key);
        } else {
            $this->error('激活失败');
        }

    }

}